//
//  KAUserManager.swift
//  kano
//
//  Created by Sophia on 2024/8/19.
//

import UIKit
import KeychainAccess

private let single = KAUserManager()

/*
 这个类将登录状态、手机号
 */
final class KAUserManager: NSObject {
    
    static var shared: KAUserManager {
        return single
    }
    
    var var_sessionId = ""
    
    let fileName: String = String(describing: KAUser.self)
    //存取用户信息
    public var user: KAUser {
        get {
            let user = KADBDBManager.ka_getUser()
            return user ?? KAUser()
        }
        set {
            KADBDBManager.ka_saveUser(data: newValue)
        }
    }
    //存取登录状态
    public var hasLogined: Bool {
        get {
            return UserDefaults.standard.bool(forKey: var_loginStatus)
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: var_loginStatus)
        }
    }
    
    func userLogin(with phone:String) {
        //登录状态
        hasLogined = true
        //存手机号是为了登录时展示
        saveUserPhone(phone)
        KAVCManager.setRooterVC()
    }
    
    func userLogout() {
//        if user.mobile == var_phone {
//            deleteApplyResult()
//        }
        hasLogined = false
        var logoutUser = user
        logoutUser.u = 0
        logoutUser.userid = 0
        logoutUser.userId = 0
        logoutUser.uid = 0
        user = logoutUser
        KAVCManager.setRooterVC()
    }
    
    //存取手机号
    private let loginedUserPhone = "loginedUserPhone"
    func saveUserPhone(_ userPhone: String) {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(userPhone)"
        let keychain = Keychain(service: service)
        keychain[loginedUserPhone] = userPhone
    }
    
    func readUserPhone(_ userPhone: String) -> String {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(userPhone)"
        let keychain = Keychain(service: service)
        if let userPhone = keychain[string: loginedUserPhone] {
            return userPhone
        }
        return ""
    }
    
    func appIsFirstLaunched(_ userPhone: String) -> Bool {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(userPhone)"
        let keychain = Keychain(service: service)
        if let userPhone = keychain[string: loginedUserPhone] {
            return userPhone.isEmpty
        } else {
            return true
        }
    }
    
    private let applyWhatsApp = "ApplyWhatsApp"
    func saveWhatsApp(_ content : String) {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(KAUserManager.shared.user.mobile)"
        let keychain = Keychain(service: service)
        keychain[applyWhatsApp] = content
    }
    func readWhatsApp() -> String {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(KAUserManager.shared.user.mobile)"
        let keychain = Keychain(service: service)
        if let applyResult = keychain[string: applyWhatsApp] {
            return applyResult
        }
        return ""
    }
    func deleteWhatsApp() {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(KAUserManager.shared.user.mobile)"
        let query: [String: Any] = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: applyWhatsApp]
        let status = SecItemDelete(query as CFDictionary)
    }
    
    
    private let applyFacebook = "ApplyFacebook"
    func saveFacebook(_ content : String) {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(KAUserManager.shared.user.mobile)"
        let keychain = Keychain(service: service)
        keychain[applyFacebook] = content
    }
    func readFacebook() -> String {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(KAUserManager.shared.user.mobile)"
        let keychain = Keychain(service: service)
        if let applyResult = keychain[string: applyFacebook] {
            return applyResult
        }
        return ""
    }
    func deleteFacebook() {
        let service = "\(Bundle.main.bundleIdentifier ?? "")_\(KAUserManager.shared.user.mobile)"
        let query: [String: Any] = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrService as String: service,
                kSecAttrAccount as String: applyFacebook]
        let status = SecItemDelete(query as CFDictionary)
    }
    
    
    class func ka_appVersion() -> String {
        if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            return version
        }
        return ""
    }
    
    
    static func appIsFirstInstall() -> Bool {
        let userDefaults = UserDefaults.standard
        
        // 检查 "everInstall" 的值是否存在
        if !userDefaults.bool(forKey: "everInstall") {
            // 第一次启动，设置 "everInstall" 和 "firstInstall" 为 true
            userDefaults.set(true, forKey: "everInstall")
            userDefaults.set(true, forKey: "firstInstall")
            return true
        } else {
            // 不是第一次启动，将 "firstInstall" 设为 false
            userDefaults.set(false, forKey: "firstInstall")
            return false
        }
    }
}
